// 云函数入口文件
const cloud = require('wx-server-sdk')
const MAX_LIMIT = 100

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const db = cloud.database()
  const _ = db.command

  const userCount = await db.collection('user').where({
    isMember: true
  }).count()
  const userTotal = userCount.total
  // 计算需分几次取
  const userBatchTimes = Math.ceil(userTotal / 100)
  const userTasks = []
  for (let i = 0; i < userBatchTimes; i++) {
    const promise = db.collection('user').where({
      isMember: true
    }).orderBy('point', 'desc').skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
    userTasks.push(promise)
  }
  const userData = (await Promise.all(userTasks)).reduce((acc, cur) => {
    return {
      data: acc.data.concat(cur.data),
      errMsg: acc.errMsg,
    }
  })
  let userList = userData.data
  console.log('userList.length',userList.length)
  for (var i = 0; i < userList.length; i++) {
    let user = userList[i]
    db.collection('userInfo').where({
      _openid: user._openid
    }).update({
      data: {
        index: user.index,
        nickName:user.nickName,
        avatarUrl:user.avatarUrl,
        isOut:user.isOut
      }
    }).then(res => {
      console.log("success:", res)
    }, error => {
      console.log("error")
    })
  }
  return {
    event,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
  }
}